<template>
  <div>
    <Card :bordered="false">
      <Row>
        <Col span="12">
        <Button type="primary" @click="openAddModal">新增</Button>&nbsp;
        <!--<Button type="primary" @click="openAddBatchModal">批量新增</Button>-->
        </Col>
        <Col span="12" style="text-align: right">
        <Select clearable v-model="selectLot.id" style="width:200px;text-align: left" placeholder="停车场">
          <Option v-for="item in lotList" :value="item.id" :key="item.name">{{ item.name }}</Option>
        </Select>
        <Input v-model="txtSearch" placeholder="设备编号" style="width: 200px"/>
        <Button icon="ios-search" type="primary" @click="getParkingSpaceList(selectLot.id)"></Button>
        </Col>
      </Row>
    </Card>
    <Card :bordered="false">
      <Table height="500" :columns="columns" :data="parkingList"></Table>
    </Card>
    <!--新增停车位-->
    <Modal
      v-model="modal.add.status"
      :title="modal.add.title"
      :top="0" @on-cancel="modalDefineCancel('modal.add.form')">
      <Form ref= 'modal.add.form' :model="modal.add.form" :label-width="80" :rules='ruleValidate'>
        <FormItem label="所属停车场" prop='lotId' :label-width="82">
          <Select clearable v-model="modal.add.form.lotId" style="width:100%;text-align: left" >
            <Option v-for="item in lotList" :value="item.id" :key="item.name">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="车位编号" prop='code'>
          <Input v-model="modal.add.form.code" placeholder="请输入车位编号" @on-blur="checkSpaceCode(modal.add.form.code)"></Input>
          <label class="codeLb" v-if="parkingCodeError">车位编号已存在</label>
        </FormItem>
        <FormItem label="设备编号" prop='deviceCode'>
          <Input v-model="modal.add.form.deviceCode" placeholder="请输入设备编号" @on-blur="checkDeviceCode(modal.add.form.deviceCode)"></Input>
          <label class="codeLb" v-if="deviceCodeError">设备编号已存在</label>
        </FormItem>
        <FormItem label="当前状态" prop='status'>
          <Select disabled clearable v-model="modal.add.form.status" style="width:100%;text-align: left">
            <Option v-for="item in spaceStatus" :value="item.key" :key="item.value">{{ item.value }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.add.form')">关闭</Button>
        <Button type="primary" @click="handleSubmit('modal.add.form',modal.add.form.lotId)">确定</Button>
      </div>
    </Modal>
    <!--修改停车位信息-->
    <Modal
      v-model="modal.update.status"
      :title="modal.update.title"
      :top="0" @on-cancel="modalDefineCancel('modal.update.form')">
      <Form ref= 'modal.update.form' :model="modal.update.form" :label-width="80" :rules='ruleValidate'>
        <FormItem label="所属停车场" prop='lotId' :label-width="82">
          <Select clearable v-model="modal.update.form.lotId" style="width:100%;text-align: left">
            <Option v-for="item in lotList" :value="item.id" :key="item.name">{{ item.name }}</Option>
          </Select>
        </FormItem>
        <FormItem label="车位编号" prop='code'>
          <Input v-model="modal.update.form.code" placeholder="请输入车位编号" @on-blur="checkSpaceCode(modal.update.form.code,modal.update.form.id)"></Input>
          <label class="codeLb" v-if="parkingCodeError">车位编号已存在</label>
        </FormItem>
        <FormItem label="设备编号" prop='deviceCode'>
          <Input v-model="modal.update.form.deviceCode" placeholder="请输入设备编号" @on-blur="checkDeviceCode(modal.update.form.deviceCode,modal.update.form.id)"></Input>
          <label class="codeLb" v-if="deviceCodeError">设备编号已存在</label>
        </FormItem>
        <FormItem label="当前状态" v-if="false" prop='status'>
          <Select clearable v-model="modal.update.form.status" style="width:100%;text-align: left">
            <Option v-for="item in spaceStatus" :value="item.key" :key="item.value">{{ item.value }}</Option>
          </Select>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="default" @click="handleReset('modal.update.form')">取消</Button>
        <Button type="primary" @click="handleSubmit('modal.update.form',modal.update.form.lotId)">确定</Button>
      </div>
    </Modal>
    <!--批量新增停车位-->
    <Modal
      v-model="modal.addBatch.status"
      :title="modal.addBatch.title"
      width="1000"
      :top="0">
      <Row>
        <Col :span="7">
        所属停车场
        <Select clearable v-model="selectLot.id" style="width:200px;text-align: left">
          <Option v-for="item in lotList" :value="item.id" :key="item.name">{{ item.name }}</Option>
        </Select>
        </Col>
        <Col :span="3">
        <Upload action="//jsonplaceholder.typicode.com/posts/">
          <Button type="primary" icon="ios-cloud-upload-outline">上传文件</Button>
        </Upload>
        </Col>
        <Col :span="4">
        <Button type="ghost" icon="ios-cloud-download-outline">下载模板</Button>
        </Col>
      </Row>

      <div slot="footer">
        <Button type="default" @click="modal.addBatch.status=false">取消</Button>
        <Button type="primary" @click="">确定</Button>
      </div>
    </Modal>
    <!--删除停车位-->
    <Modal
      v-model="modal.delete.status"
      :title="modal.delete.title">
      确定删除此停车位（编号{{modal.delete.spaceName}}）吗？
      <div slot="footer">
        <Button type="default" @click="modal.delete.status=false">取消</Button>
        <Button type="error" @click="deleteParkingSpace(modal.delete.lotId)">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
  import urlSource from '../../api/urlSource'
  import moment from 'moment'

  export default {
    name: "space",
    components: {},
    data() {
      let validateLotId = function(rule, value, callback){
        if(!value){
          return callback(new Error("请选择停车场"));
        }else{
          callback();
        }
      };
      let validateCode = function(rule, value, callback){
        if(!value){
          this.parkingCodeError = false;
          return callback(new Error("请输入车位编号"));
        }else{
          callback();
        }
      };
      let validateDeviceCode = function(rule, value, callback){
        if(!value){
          return callback(new Error("请输入设备编号"));
        }else{
          callback();
        }
      };
      let validateStatus = function(rule, value, callback){
        if(!value){
          return callback(new Error("请选择当前状态"));
        }else{
          callback();
        }
      };
      return {
        modal: {
          add: {
            status: false,
            title: "新增停车位",
            form: {
              id: "",
              code: "",
              lotId: "",
              deviceCode: "",
              status: 2,
              createTime: "",
            }
          },
          update: {
            status: false,
            title: "修改停车位",
            form: {
              id: "",
              code: "",
              lotId: "",
              deviceCode: "",
              status: "",
              createTime: "",
              updateTime: ""
            },
          },
          addBatch: {
            status: false,
            title: "批量新增停车位"
          },
          delete: {
            status: false,
            title: "系统提示",
            spaceName: "",
            id: "",
          }
        },
        lotList: [],//停车场列表
        selectLot: {
          id: "",
          name: ""
        },
        spaceStatus: [
          {
            key: 0,
            value: "空闲",
          },
          {
            key: 1,
            value: "占有",
          },
          {
            key: 2,
            value: "初始化",
          },
          {
            key: 3,
            value: "初始化失败",
          },
          {
            key: 4,
            value: "空闲临界",
          },
          {
            key: 5,
            value: "占有临界",
          }
        ],
        txtSearch: "",
        columns: [
          {
            type: 'index',
            width: 60,
            align: 'center'
          },
          {
            title: '车位编号',
            key: 'code'
          },
          {
            title: '设备编号',
            key: 'deviceCode'
          },
          {
            title: '所属停车场',
            key: 'lotId',
            render: (h, params) => {
              var parkingLotName = "";
              this.lotList.forEach(v => {
                if (v.id == params.row.lotId) {
                  parkingLotName = v.name;
                }
              })
              return h('div', [
                h('div', parkingLotName)
              ]);
            }
          },
          {
            title: '创建时间',
            key: 'createTime',
          },
          {
            title: '操作',
            key: 'id',
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'primary',
                    size: 'small'
                  },
                  style: {
                    marginRight: '5px'
                  },
                  on: {
                    click: () => {
                      this.modal.update.status = true;
                      this.modal.update.form = JSON.parse(JSON.stringify(params.row));
                      this.modal.update.form.status = parseInt(this.modal.update.form.status);
                    }
                  }
                }, '修改'),
                h('Button', {
                  props: {
                    type: 'error',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.modal.delete.status = true;
                      this.modal.delete.spaceName = params.row.code;
                      this.modal.delete.id = params.row.id;
                      this.modal.delete.lotId = params.row.lotId;
                    }
                  }
                }, '删除'),

              ]);
            }
          }
        ],
        parkingList: [],
        deviceCodeError: false,
        parkingCodeError: false,
        ruleValidate:{
          lotId : [{required: true,validator: validateLotId,type: 'string', message: '请选择停车场',trigger: 'change'}],
          code : [{required: true,validator: validateCode,trigger: 'blur'}],
          deviceCode : [{required: true,validator: validateDeviceCode,trigger: 'blur'}],
          status : [{required: true,validator: validateStatus,trigger: 'blur'}],
        },
      }
    },
    methods: {
      handleReset (name) {
        if(name=='modal.add.form'){
          this.modal.add.status=false;
        }else{
          this.modal.update.status=false;
        }
        this.deviceCodeError = false;
        this.parkingCodeError = false;
        this.$refs[name].resetFields();
      },
      modalDefineCancel (name){
        this.deviceCodeError = false;
        this.parkingCodeError = false;
        this.$refs[name].resetFields();
      },
      handleSubmit (name,lotId) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            if(this.deviceCodeError){
              this.$Message.error('请正确填写设备编号');
              return;
            }
            if(this.parkingCodeError){
              this.$Message.error('请正确填写车位编号');
              return;
            }
            if(name=='modal.add.form'){//添加表单校验
              this.addParkingSpace(lotId);
            }else{//修改表单校验
              this.updateParkingSpace(lotId);
            }
          } else {
            this.$Message.error('请正确填写信息');
          }
        })
      },
      //校验设备编号
      checkDeviceCode(deviceCode,id){
        if(deviceCode!=null && deviceCode!='' && deviceCode!=undefined){
          let url = urlSource.apiUrl + 'parkingSpaces/checkDeviceCode';
          let param = {deviceCode:deviceCode};
          param.id = id ? id : null;
          this.$http.post(url,param).then(res => {
            this.deviceCodeError = res.data;
          }).catch(err => {

          })
        }else{
          this.deviceCodeError = false;
        }
      },
      //校验停车位编号
      checkSpaceCode(spaceCode,id){
        if(spaceCode!=null && spaceCode!='' && spaceCode!=undefined){
          let url = urlSource.apiUrl + 'parkingSpaces/checkSpaceCode';
          let param = {code:spaceCode};
          param.id = id ? id : null;
          this.$http.post(url,param).then(res => {
            this.parkingCodeError = res.data;
          }).catch(err => {

          })
        }else{
          this.parkingCodeError = false;
        }
      },
      //获取停车场列表
      getParkingLot() {
        let url = urlSource.apiUrl + "parkingLots/" + this.$store.state.user.orgId + "/all"
        this.$http.get(url).then(res => {
          this.lotList = res.data
          this.selectLot.id = this.lotList[0].id;
          this.getParkingSpaceList(this.selectLot.id);
        }).catch(err => {

        })
      },
      //获取停车位列表
      getParkingSpaceList(lotId) {
        if(!lotId){
          this.$Message.warning('请先选择停车场');
          return ;
        }
        let url = urlSource.apiUrl + "parkingSpaces/lots/" + lotId;
        if(this.txtSearch){
          url += '?devCode=' + this.txtSearch;
        }
        this.$http.get(url).then(res => {
          if (res.data != "" && res.data != null) {
            this.parkingList = res.data;
          } else {
            this.parkingList = []
          }
        }).catch(err => {

        })
      },
      //打开新增停车位窗口
      openAddModal() {
        this.modal.add.status = true;
        this.modal.add.form.lotId = this.selectLot.id;
      },
      //打开批量新增停车位窗口
      openAddBatchModal() {
        this.modal.addBatch.status = true;
      },
      //新增停车位
      addParkingSpace(lotId) {
        let url = urlSource.apiUrl + "parkingSpaces/add";
        this.$http.post(url, this.modal.add.form).then(res => {
          if (res.data) {
            this.$refs['modal.add.form'].resetFields();
            this.$Message.success("新增成功!");
            this.getParkingSpaceList(lotId);
            this.selectLot.id = lotId;
            this.modal.add.status = false;
          } else {
            this.$Message.error("新增失败!");
          }
        }).catch(err => {
          this.$Message.error("新增失败!");
        })
      },
      //删除停车位
      deleteParkingSpace(lotId) {
        let url = urlSource.apiUrl + "parkingSpaces/delete/" + this.modal.delete.id;
        this.$http.delete(url).then(res => {
          if (res.data) {
            this.$Message.success("删除成功!");
            this.modal.delete.status = false;
            this.getParkingSpaceList(lotId)
          } else {
            this.$Message.error("删除失败!");
          }
        }).catch(err => {
          this.$Message.error("删除失败!");
        })
      },
      //修改停车位信息
      updateParkingSpace(lotId) {
        let url = urlSource.apiUrl + "parkingSpaces/update";
        this.modal.update.form.createTime = new Date(this.modal.update.form.createTime);
        if (this.modal.update.form.updateTime != "" && this.modal.update.form.updateTime != null) {
          this.modal.update.form.updateTime = new Date(this.modal.update.form.updateTime);
        }
        this.$http.put(url, this.modal.update.form).then(res => {
          if (res.data) {
            this.$Message.success("修改成功!");
            this.modal.update.status = false;
            this.getParkingSpaceList(lotId)
            this.selectLot.id = lotId;
            this.modal.update.status = false;
          } else {
            this.$Message.error("修改失败!");
          }
        }).catch(err => {
          this.$Message.error("修改失败!");
        })
      }
    },
    mounted() {
      this.$nextTick(() => {
        this.getParkingLot();
      })
    }
  }
</script>

<style lang="less">
  .vertical-center-modal {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .ivu-modal {
    top: 2px;
  }
  .codeLb{
    position: absolute;
    padding-top: 6px;
    line-height: 1;
    color: #ed3f14;
    top: 100%;
    left: 0;
  }
</style>
